from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse

from .myforms import StudentForm
from .models import Student

from django.shortcuts import reverse


# from django.urls.base import reverse,resolve

# Create your views here.
# todo
def index(request):
    if request.method == "GET":
        form = StudentForm()  # 创建form组件 modelform
        return render(request, 'student2.html', {"form": form})
    if request.method == "POST":
        # name = request.POST.get("name", "")
        # age = request.POST.get("age", "")
        form = StudentForm(request.POST)
        if form.is_valid():
            # 经过验证合法的值 放到cleaned_data中 这是一个字典
            # print(form.cleaned_data)
            # print(type(form.cleaned_data))
            student = Student(**form.cleaned_data)
            student.save()
        else:
            return render(request, 'student2.html', {"form": form})
        return HttpResponse("ok")


# 根据路由的名称,找到路由的绝对路径 --> 路由的反向解析

def getpath(request):
    # res = reverse('student2:index')
    # res = reverse('blog2:add_blog') # 解析其他应用下的路径
    # res = reverse('blog2:blog', args=[1, ])  # 通过args传参
    res = reverse('blog:blog_detail')  # 通过kwargs传参
    # print(res)  # 应用名:路径名称  app_name:view_name
    # / blog / blog_detail /?id=xx
    res = '{}?id={}'.format(res,'1')
    print('-------getpath---------------',id(request))
    return render(request, 'rev.html')
    # return redirect(res)
